// pages/function/schedule/schedule.js
import { behavior as computedBehavior } from 'miniprogram-computed';
Page({
  behaviors: [computedBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    weekList: [],
    customWeekIndex: 0,
    currentWeekIndex: 0,
    fullWeek: false,
    weekDay: [
      ["周一"],
      ["周二"],
      ["周三"],
      ["周四"],
      ["周五"],
      ["周六"],
      ["周日"],
    ],
    currentDay: 1,
    weather: [],
    weatherShow: false,
    timeTable: [
      `08:00\n08:45`,
      `08:55\n09:40`,
      `10:00\n10:45`,
      `10:55\n11:40`,
      `13:00\n13:45`,
      `13:55\n14:40`,
      `14:50\n15:35`,
      `15:45\n16:30`,
      `16:40\n17:25`,
      `17:35\n18:20`,
    ],
    schedule: []
  },

  watch: {
    "customWeekIndex": function (newValue) {
      const [get, set] = getApp().Storage.use('customWeekIndex')
      if (get() == newValue) return;
      else {
        let beginDay = new Date(getApp().Storage.get('beginDay')).getTime()
        let weekDay = this.getWeekInfo(new Date(beginDay + newValue * (7 * 24 * 60 * 60 * 1e3)))
        // console.log(weekDay);
        this.setData({
          weekDay
        })
        this.checkHidden()
        set(newValue)
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const nowDate = new Date();
    const currentDay = nowDate.getDay()
    const week = this.getWeekInfo(nowDate);
    this.setData({
      weekList: Array(20).fill(0).map((_, i) => `${i + 1}周`),
      fullWeek: getApp().Storage.get('fullWeek') || false,
      currentDay,
      weekDay: week,
      navTop: getApp().globalData.navTop,
      heightConfig: getApp().globalData.windowHeight,
      widthConfig: getApp().globalData.windowWidth,
    })
    this.getBeginDay()
    this.getWeather()
    if (!getApp().Storage.get('isBinding')) {
      wx.navigateTo({
        url: '/pages/bind/bind?back=' + true,
      })
    } else this.getSchedule()
  },
  getWeekInfo(aDate) {
    if (!(aDate instanceof Date)) aDate = new Date(aDate)
    const currentDay = aDate.getDay()
    const MonDate = currentDay == 1 ? aDate : new Date(aDate.getTime() - ((currentDay - 1) * (24 * 60 * 60 * 1e3)))
    const week = Array(7).fill(0).map((_, i) => {
      let date = new Date(MonDate.getTime() + i * (24 * 60 * 60 * 1e3))
      let weekDay = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
      return [
        weekDay[i],
        `${date.getMonth() + 1}-${date.getDate()}`
      ]
    })
    return week
  },
  getBeginDay() {
    let [nowBegin, setBegin] = getApp().Storage.use('beginDay');
    if (nowBegin()) {
      let nowMonth = new Date().getMonth()
      let beginMonth = new Date(nowBegin()).getMonth()
      if (nowMonth - beginMonth < 6) {
        this.setCurrentWeek(nowBegin())
        return;
      }
    }
    getApp().requestWithToken.get('/class/schedule/getBeginTime').then(({ code, data }) => {
      if (code != 200) return;
      setBegin(data)
      this.setCurrentWeek(data)
    })
  },
  setCurrentWeek(str) {
    if (!(str instanceof Date)) str = new Date(str)
    const currentDay = str.getDay()
    const MonDate = new Date(str.getTime() - ((currentDay - 1) * (24 * 60 * 60 * 1e3)))
    const nowDate = new Date()
    let currentWeekIndex = Math.floor(((nowDate - MonDate) / (24 * 60 * 60 * 1e3)) / 7)
    this.setData({
      customWeekIndex: currentWeekIndex,
      currentWeekIndex
    })
  },
  getWeather() {
    getApp().requestWithToken.get('/class/schedule/getWeather', {
      data: {
        city: '衡阳'
      }
    }).then(({ code, data }) => {
      if (code !== 200) return;
      this.setData({
        weather: data
      })
    })
  },
  getSchedule() {
    getApp().requestWithToken.get('/class/schedule/getClassSchedule').then(({ code, data }) => {
      if (code !== 200) return;
      data.forEach(_ => {
        _.color = this.randomColor(_.title)
      })
      this.setData({
        schedule: data,
      })
      this.checkHidden()
    })
  },
  getWeekList(str) {
    return new Set(String.prototype.split.call(str, ',').map(item => {
      let arr = item.split('-').map(i => i * 1)
      let list = []
      if (arr[1]) {
        for (let i = arr[0]; i <= arr[1]; i++) {
          list.push(i)
        }
      } else list.push(arr[0] * 1)
      return list
    }).flat())
  },
  checkHidden() {
    const schedule = this.data.schedule.map(_ => {
      _.hidden = !this.getWeekList(_.week).has(this.data.customWeekIndex * 1 + 1)
      return _
    })
    this.setData({
      schedule
    })
  },
  randomColor(str) {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    const s = '50%'; // Saturation
    const l = '70%'; // Lightness
    const h = ((Math.abs(hash) % 270) + 1) / 360 * 100; // Hue
    return `hsl(${h}, ${s}, ${l})`;
  },
  changeShow() {
    if (!this.data.weather.length) return;
    this.setData({
      weatherShow: !this.data.weatherShow
    })
  },
  langTap(e) {
    console.log(e);
    return e
  },
  addNote(e) {
    console.log(e);
  },
  changeFullWeek() {
    let fullWeek = !this.data.fullWeek
    getApp().Storage.set('fullWeek', fullWeek)
    this.setData({
      fullWeek
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (!this.schedule || !this.schedule.length) return;
    this.getSchedule()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})